﻿using System;
using System.Management;
using System.Diagnostics;

namespace Confessor
{
    class Interogation
    {
        XFileActions xFA = new XFileActions();
        string targetHost;
        bool canConnect = false;

        /// <summary>
        /// Main Method for doing work.  Controls the workflow.
        /// </summary>
        /// <param name="scanObject"></param>
        /// <param name="y"></param>
        public void InitiateWMI(ScanObject scanObject, int y)
        {
            // set the variables for Target Host and Scan Server
            targetHost = scanObject.Hosts[y].IP.ToString();

            ConnectionOptions oConn = new ConnectionOptions();
            oConn.Username = scanObject.UserName;
            oConn.Password = scanObject.Password;

            // Set up the WMI Management Objects
            ManagementScope mScope = new ManagementScope(@"\\" + targetHost + @"\root\cimv2");
            ManagementClass mClass = new ManagementClass(mScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());

            // Run through the interogation
            verifyWMI(mScope, mClass, scanObject);
            if(canConnect == true)
            {
                try
                {
                    setTargetHostname(mScope, scanObject, y);

                    //create directory for results of host scan
                    string directory = scanObject.ResultsDirectory + @"\" + scanObject.Hosts[y].HostName;
                    xFA.MakeDirectory(directory);
                }
                catch (Exception ex)
                {
                    string statusMessage = targetHost + ": " + ex.Message;
                    xFA.WriteToErrorLog(statusMessage, scanObject);
                }
            }

            if (canConnect == true)
            {
                try
                {
                    startRemoteFile(scanObject, mScope, mClass, y);
                }
                catch (Exception ex)
                {
                    string statusMessage = targetHost + ": " + ex.Message;
                    xFA.WriteToErrorLog(statusMessage, scanObject);
                }
            }
        }

        /// <summary>
        /// The many WMI connection Methods
        /// </summary>
        /// <param name="targetHost"></param>
        /// 

        // Verify WMI Connectivity.
        private void verifyWMI(ManagementScope mScope, ManagementClass mClass, ScanObject scanObject)
        {
            object[] command = { "testConnectivity" };
            
            try
            {
                mClass.InvokeMethod("Create", command);
                canConnect = true;
            }
            catch (Exception ex)
            {
                canConnect = false;
                string statusMessage = targetHost + " " + ex.Message;
                xFA.WriteToErrorLog(statusMessage, scanObject);
            }
        }

        // Set the variable targetHostName
        private void setTargetHostname(ManagementScope mScope, ScanObject scanObject, int y)
        {
            // Set the variable TargetHostName
            SelectQuery qryHostName = new SelectQuery("Win32_ComputerSystem");
            ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(mScope, qryHostName);

            foreach (ManagementBaseObject compVar in mSearcher.Get())
            {
                scanObject.Hosts[y].HostName = compVar["Name"].ToString();
                if (scanObject.Hosts[y].HostName == string.Empty)
                {
                    scanObject.Hosts[y].HostName = scanObject.Hosts[y].IP;
                }
            }
        }

        // Start Gathering Data (Start a remote file).
        private void startRemoteFile(ScanObject scanObject, ManagementScope mScope, ManagementClass mClass, int y)
        {
            // normal command
            object[] command = { scanObject.ResultsSharePath + @"\" + scanObject.InvestigationID + @"\confess.bat " + scanObject.ConfessorSharePath + " " + scanObject.ResultsSharePath + @"\" + scanObject.InvestigationID + @"\" + scanObject.Hosts[y].HostName };
                        
            try
            {
                // Create the process that will execute the batch script.
                mClass.InvokeMethod("Create", command);
                scanObject.Hosts[y].Scan_Start = DateTime.Now.ToString();
            }
            catch (Exception e)
            {
                string statusMessage = targetHost + " Failed: " + e.Message;
                xFA.WriteToErrorLog(statusMessage, scanObject);
            }
        }

        // Get Process ID's of Remote Host
        private void getProcessId(ManagementScope mScope, ManagementClass mClass)
        {
            // Build a query for enumeration of Drives and Network Drives
            SelectQuery query = new SelectQuery("Win32_Process");

            // Instantiate an object searcher with this query. (Scope is the management scope package)
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(mScope, query);
            foreach (ManagementBaseObject procVar in searcher.Get())
            {
                string processName = procVar["Name"].ToString();
            }
        }
    }
}
